package com.lib76.buildCode.service;

import java.util.LinkedHashMap;

import org.apache.commons.lang.StringUtils;

import com.lib76.buildCode.model.Menu;
import com.lib76.buildCode.model.PageEntity;

public class MenuConfigServer {
	
	/**
	 * 页面对象转换菜单对象
	 * @param page
	 * @return
	 */
	public static Menu pageToMenu(PageEntity page){
		Menu menu = new Menu();
		menu.setCode(page.getEntityClassName());
		menu.setName(page.getEntityChinaName());
		menu.setUrl("/manage/"+StringUtils.uncapitalize(page.getEntityClassName())+"/list");
		return menu;
	}

	/**
	 * 查找菜单
	 * @param menus
	 * @param id
	 * @return
	 */
	public static Menu findMenu(LinkedHashMap<String,Menu> menus,String id){
		String[] path = id.split("\\.");
		if(path.length == 2){
			return menus.get(path[1]);
		}else if(path.length > 2){
			Menu result = null;
			for(int i=1;i<path.length;i++){
				result = menus.get(path[i]);
				if(i==(path.length-1)){
					return result;
				}else if(result != null && result.getChildren() != null){
					menus = result.getChildren();
				}else{
					return null;
				}
			}
		}
		return null;
	}
	
	/**
	 * 保存菜单
	 * @param menus
	 * @param menu
	 * @return
	 */
	public static void saveMenu(LinkedHashMap<String,Menu> menus,Menu menu){
		Menu parent = findMenu(menus,menu.getParent());
		if(parent != null){
			if(parent.getChildren()==null){
				parent.setChildren(new LinkedHashMap<String,Menu>());
			}
			parent.getChildren().put(menu.getCode(),menu);
		}else{
			menus.put(menu.getCode(), menu);
		}
	}
	
	/**
	 * 移动一个菜单到另一个菜单下面
	 * @param menus
	 * @param srcId
	 * @param targetId
	 * @return
	 */
	public static boolean moveTo(LinkedHashMap<String,Menu> menus,String srcId,String targetId){
		String srcParentId = srcId.substring(0,srcId.lastIndexOf("."));
		String srcCode = srcId.substring(srcId.lastIndexOf(".") + 1);
		Menu srcMenu = null;
		if("root".equals(srcParentId)){
			srcMenu = menus.remove(srcCode);
		}else{
			Menu srcParent = findMenu(menus,srcParentId);
			if(srcParent != null && srcParent.getChildren() != null){
				srcMenu = srcParent.getChildren().remove(srcCode);
			}
		}
		if(srcMenu != null){
			Menu targetMenu = findMenu(menus,targetId);
			if(targetMenu != null){
				if(targetMenu.getChildren()==null){
					targetMenu.setChildren(new LinkedHashMap<String,Menu>());
				}
				srcMenu.setParent(targetId);
				targetMenu.getChildren().put(srcMenu.getCode(), srcMenu);
				return true;
			}
		}
		return false;
	}
}
